package com.atguigu.gmall.cart.controller;


import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Description: 加入购物车
 * @Author: Mr.Cao
 * @DateTime: 2021/10/11 20:03
 * BMW F750GS
 **/
@RestController
@RequestMapping("/api/cart")
public class CartInfoApiController {

    @Autowired
    private CartInfoService cartInfoService;

    /**
     * 加入购物车 ==加
     * */
    @PostMapping("/addToCart/{skuId}/{skuNum}")
    public CartInfo addToCart(
            @PathVariable Long skuId,
            @PathVariable Integer skuNum
    ){
        String userId = getUserIdOrTempUserId();
        return cartInfoService.addToCart(skuId,skuNum,userId);
    }
    /**
     * 加入购物车 == 查 用于跳转到加入购车页面的数据回显
     * */
    @GetMapping("/toCart/{skuId}")
    public CartInfo toCart(@PathVariable Long skuId){
        String userId = getUserIdOrTempUserId();
        return cartInfoService.toCart(skuId,userId);
    }

    //获取用户Id
    private String getUserIdOrTempUserId() {
        //任意位置 获取Request对象
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        //从请求头中获取用户Id 拦截器中已经将用户Id设置到请求头中
        //AuthContextHolder.getUserId(request)封装好的工具类, 从请求头中获取用户Id
        String userId = null;
        if (!StringUtils.isEmpty(AuthContextHolder.getUserId(request))){
            userId =AuthContextHolder.getUserId(request);

        }else {
            userId =AuthContextHolder.getUserTempId(request);
        }
        return userId;
    }

    //初始化加载购物车集合   当前用户的所有的购物车集合
    //当前用户：
    // 如果登录了应该查询（真实用户的 + 临时用户的）  临时用户的购物车清空
    // 如果未登录是临时用户的
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request) {
        //真实用户的ID
        String userId = AuthContextHolder.getUserId(request);
        //临时用户的ID
        String userTempId = AuthContextHolder.getUserTempId(request);
        //查询购物车集合
        List<CartInfo> cartInfoList = cartInfoService.cartList(userId, userTempId);
        return Result.ok(cartInfoList);
    }


     /**
      * 去结算页面显示,已经选中的商品
      * */
    @GetMapping("getCartInfoListByChecked")
    public List<CartInfo> getCartInfoListByChecked(HttpServletRequest request){
        //获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        List<CartInfo> list =  cartInfoService.getCartInfoListByChecked(userId);
        return list;
    }
}
